<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Product extends Backend {

	public function __construct()
	{
		parent::__construct();
		$this->lang->load('sites');
		$this->load->model(['site_model','sitecategory_model','goods_model','siteproduct_model','siteuser_model','siteorder_model','sitedisapproved_model']);
		$this->data['page_home']  = lang('lang_dashboard');
		$this->data['page_title'] = lang('lang_site');
		$this->data['sitetype'] = $this->config->item('site_types');

	}


	public function index($siteid)
	{

		$site=$this->site_model->getitembyid($siteid);
		if(!$site) die('error link');

		$this->data['nav']=$this->get_site_nav($site,2);

		$this->data['checkapi']=$this->mysite->checklink;

		$this->data['site']=$site;
		// Title
		$this->data['meta_title'] = $this->data['page_title'];

		// Breadcrumbs
		$this->data['array_breadcrumbs'] = array(
			$this->data['page_home']  => 'backend',
			$this->data['page_title'] => 'backend/sites/site',
			'站点产品'=>'backend/sites/product'
		);

		$key=trim($this->input->get('keyword'));
        $page=max(1,(int) $this->input->get('page'));        
        $pagesize=intval($this->input->get('pagesize'));
        if($pagesize){
            set_cookie("pagesize",$pagesize,60*60*24);
        }else{
            $pagesize=get_cookie("pagesize");
		}
		
		$page_data=$this->siteproduct_model->getpage($siteid,$page,$pagesize,$key);

		$pid=[];
		foreach($page_data["data"] as $item)
		{
			$pid[]=$item["productid"];
		}
		if($pid)
		{
			$sourceurl=[];
			$goodoption=[];
			$where="id in (".implode(",",$pid).")";
			$goods=$this->goods_model->get_items_by_where_fix($where);
			if($goods)
			{
				foreach($goods as $g)
				{
					$sourceurl[$g["id"]]=$g["source_url"];
					$goodoption[$g["id"]]=unserialize($g["option"]);
				}
			}
			$this->data['sourceurl']=$sourceurl;
			$this->data['goodoption']=$goodoption;
		}
		
		$this->data['loglist']=$page_data["data"];
		$this->data['pager']=$page_data["pager"]; 
		$this->data['total']=$page_data["total"];
        $this->data['pages']=$page_data["pages"];
		$this->data['page']=$page;   
		   
		$keyword = array(
			'name'      => 'keyword',
			'id'        => 'keyword',
			'value'     =>  $key,
			'class'     =>  'form-control input-sm',
			'placeholder'=> '请输入关键字',
			'maxlength' => '100'
		);
		$this->data['keyword']=$keyword;
		

		$this->data['content_header_title'] = content_header_title($this->data['page_title'],$site['name'].' 产品');
		$this->data['content'] = 'sites/product';

		$this->render();
	}

	public function sync($siteid)
	{
		$site=$this->site_model->getitembyid($siteid);
		if(!$site) die('error link');
		$returndata=["status"=>0,"msg"=>""];
		loadsystemlink($site);
		if($this->mysite->checklink)
		{
			$cats=$this->sitecategory_model->getcat($siteid);
			$returninfo=$this->mysite->synccatrgory($cats);
			foreach($returninfo as $k=>$v)
			{
				$newdata=["rid"=>$v];
				$this->sitecategory_model->update($k, $newdata);
			}
			$returndata["status"]=1;			
		}
		else
		{
			$returndata["msg"]="接口连接错误，请检查";
		}
		echo json_encode($returndata,JSON_UNESCAPED_UNICODE);
		die();
	}


    public function ajaxedit()
    {
		$return=["status"=>1];
        $attrName=$this->input->post("attrName");
		$newHtml=$this->input->post("newHtml");
		if(!in_array($attrName,['title','price'])) die();
		$cid=$this->input->post("cid");
		
		$product=$this->siteproduct_model->getitembyid($cid);
		if(!$product)
		{
			$return["status"]=0;
			$return["msg"]="记录不存在";			
		}
		else
		{
			$site=$this->site_model->getitembyid($product["siteid"]);
			loadsystemlink($site);
		

			if(!$this->mysite->checklink)
			{
				$return["status"]=0;
				$return["msg"]="请检查接口配置";	
			}
			else
			{
				$newdata[$attrName]=$newHtml;

				/*
				if($site["sitetype"]==2 && $attrName=="price")
				{
					$comprice=$this->input->post("comprice");
					$newdata["compare_at_price"]=$comprice;
				}
				*/

				$result = $this->mysite->updatepro($product["rid"],$newdata);
				if($result=="ok")
				{
					//if($site["sitetype"]==2 && $attrName=="price")
					//unset($newdata["compare_at_price"]);				
					$this->siteproduct_model->update($cid, $newdata);
				}
			}
		}

        echo json_encode($return);
        die();
	}

	public function querysubprice2($cid)
	{
		$return=["status"=>0,"msg"=>"失败"];
		$product=$this->siteproduct_model->getitembyid($cid);
		if(!$product)
		{
			$return["msg"]="记录不存在";			
		}
		else
		{
			$site=$this->site_model->getitembyid($product["siteid"]);
			if($site["sitetype"]==1)
			{
				loadsystemlink($site);
				if($this->mysite->checklink)
				{
					$opprice=[];
					$post=["rid"=>$product["rid"]];
					$result = $this->mysite->getopprice2($post);					
					if($result)
					{
						$result = json_decode($result,true);
						$newresult=[];
						foreach($result as $k=>$v)
						{
							$opprice[]=["opname"=>$v["name"],"opid"=>$v["id"],"opval"=>$v["price"]];
						}
						$return["status"]=1;
						$return["opprice"]=$opprice;
					}
				}
				else
				{
					$return["msg"]="目标网站无法链接，请检查";
				}
				unset($this->mysite);
			}
			else
			{
				$return["msg"]="该功能不支持此类型网站";
			}
		}
		echo json_encode($return,JSON_UNESCAPED_UNICODE);
		die();
	}


	public function subopprice2()
	{
		$return=["status"=>0,"msg"=>"更新失败"];
		$rid=$this->input->post("rid");	
		$opprice=$this->input->post("opprice");
		$opid=$this->input->post("opid");
		$siteid=$this->input->post("siteid");

		
		foreach($opprice as $k=>$p)
		{
			$p=floatval($p);
			$p= sprintf("%.2f",$p);
			if($p>0)
			{
				$opvalue[$opid[$k]]=$p;
			}
		}
		if($opvalue)
		{
			$site=$this->site_model->getitembyid($siteid);
			if($site["sitetype"]==1)
			{
				loadsystemlink($site);
				if($this->mysite->checklink)
				{
					$post=["rid"=>$rid,"opprice"=>$opvalue];
					$result = $this->mysite->opprice2($post);
					$return["status"]=1;
				}
				else
				{
					$return["msg"]="目标网站无法链接，请检查";
				}
				unset($this->mysite);
			}
			else
			{
				$return["msg"]="该功能不支持此类型网站";
			}
		}
		echo json_encode($return,JSON_UNESCAPED_UNICODE);
		die();
	}


	public function querysubprice($cid)
	{		
		$return=["status"=>0,"msg"=>"失败"];
		$product=$this->siteproduct_model->getitembyid($cid);
		if(!$product)
		{
			$return["msg"]="记录不存在";			
		}
		else
		{
			$site=$this->site_model->getitembyid($product["siteid"]);
			if($site["sitetype"]==1)
			{
				loadsystemlink($site);
				if($this->mysite->checklink)
				{
					$post=["rid"=>$product["rid"]];
					$result = $this->mysite->getopprice($post);					
					if($result)
					{
						$result = json_decode($result,true);
						$newresult=[];
						foreach($result as $k=>$v)
						{
							$newresult[strtolower(trim($k))]=$v;
						}
						$og=$this->goods_model->getbyid($product["productid"]);
						if($og)
						{
							$opprice=[];
							$agval=[];
							$og["option"]=unserialize($og["option"]);
							if(isset($og["option"]["vv"][0]["price"]) && $og["option"]["vv"][0]["value"])
							{
								$agval=$og["option"]["vv"][0]["value"];
							}
							else if(isset($og["option"]["vv"][1]["price"]) && $og["option"]["vv"][1]["value"])
							{
								$agval=$og["option"]["vv"][1]["value"];
							}
							if($agval)
							{
								foreach($agval as $v)
								{
									if(isset($newresult[strtolower(trim($v))]))
									{
										$opprice[]=$newresult[strtolower(trim($v))];
									}
									else
									{
										$opprice[]=0;
									}
								}
								$return["status"]=1;
								$return["opprice"]=$opprice;
							}
						}
						else
						{
							$return["msg"]="产品数据已丢失";
						}

					}
				}
				else
				{
					$return["msg"]="目标网站无法链接，请检查";
				}
				unset($this->mysite);
			}
			else
			{
				$return["msg"]="该功能不支持此类型网站";
			}
		}
		echo json_encode($return,JSON_UNESCAPED_UNICODE);
		die();
	}

	public function subopprice()
	{
		$return=["status"=>0,"msg"=>"更新失败"];
		$rid=$this->input->post("rid");
		$siteid=$this->input->post("siteid");
		$opname=$this->input->post("opname");
		$opprice=$this->input->post("opprice");
		$opvalue=[];
		foreach($opprice as $k=>$p)
		{
			$p=floatval($p);
			$p= sprintf("%.2f",$p);
			if($p>0)
			{
				$opvalue[$opname[$k]]=$p;
			}
		}
		if($opvalue)
		{
			$site=$this->site_model->getitembyid($siteid);
			if($site["sitetype"]==1)
			{
				loadsystemlink($site);
				if($this->mysite->checklink)
				{
					$post=["rid"=>$rid,"opvalue"=>$opvalue];
					$result = $this->mysite->opprice($post);
					$return["status"]=1;
				}
				else
				{
					$return["msg"]="目标网站无法链接，请检查";
				}
				unset($this->mysite);
			}
			else
			{
				$return["msg"]="该功能不支持此类型网站";
			}
		}
		echo json_encode($return,JSON_UNESCAPED_UNICODE);
		die();
	}


	public function syncimages($gid)
	{
		$json=["status"=>0,"msg"=>"同步失败"];
		$good=$this->goods_model->getbyid($gid);
		$config = get_system_settings(); 
		if($good)
		{
			$todo=$this->siteproduct_model->getitemsfilter(["productid"=>$gid]);
			if($todo)
			{
				foreach($todo as $to)
				{
					$site=$this->site_model->getitembyid($to["siteid"]);
					if($site["sitetype"]!=1) continue;
				
					$todogood=["rid"=>$to["rid"]];
					$todogood["thumb"]=unserialize($good["thumb"]);
					if($todogood["thumb"]):
					foreach($todogood["thumb"] as &$img)
					{
						if(substr($img,0,4)!="http")
						{
							$img=$config["urlpath"].'/'.$img;
						}
					}
					endif;
					$todogood["option"]=unserialize($good["option"]);
					loadsystemlink($site);
					if($this->mysite->checklink)
					{
						$result = $this->mysite->syncimages($todogood);
					}
					unset($this->mysite);

				}
				$json["status"]=1;
			}
			else
			{
				$json["msg"]="未找到发布产品";
			}				
		}
		else
		{
			$json["msg"]="商品不存在";
		}
		echo json_encode($json,JSON_UNESCAPED_UNICODE);
		die();
	}


	public function syncdesc($gid)
	{
		$json=["status"=>0,"msg"=>"同步失败"];
		$good=$this->goods_model->getbyid($gid);
		if($good)
		{
			$todo=$this->siteproduct_model->getitemsfilter(["productid"=>$gid]);
			if($todo)
			{
				foreach($todo as $to)
				{
					$site=$this->site_model->getitembyid($to["siteid"]);
					if($site["sitetype"]!=1) continue;
				
					$todogood=["rid"=>$to["rid"],"desc"=>$good["desc"]];
					
					loadsystemlink($site);
					if($this->mysite->checklink)
					{
						$result = $this->mysite->syncdesc($todogood);
					}
					unset($this->mysite);

				}
				$json["status"]=1;
			}
			else
			{
				$json["msg"]="未找到发布产品";
			}				
		}
		else
		{
			$json["msg"]="商品不存在";
		}
		echo json_encode($json,JSON_UNESCAPED_UNICODE);
		die();
	}

	public function synccombine($gid)
	{
		$json=["status"=>0,"msg"=>"同步失败"];
		$good=$this->goods_model->getbyid($gid);
		if($good)
		{
			$good["option"]=unserialize($good["option"]);			
			foreach($good["option"]["vv"] as $k=>$option){				
				if(strstr(strtolower($option["name"]),"color") || strstr(strtolower($option["name"]),"colour"))
				{
					$good["option"]["vv"][$k]["name"]="Color";
				}
				if(strstr(strtolower($option["name"]),"size"))
				{
					$good["option"]["vv"][$k]["name"]="Size";
				}				
			}
			$todo=$this->siteproduct_model->getitemsfilter(["productid"=>$gid]);
			if($todo)
			{
				foreach($todo as $to)
				{
					$site=$this->site_model->getitembyid($to["siteid"]);
					if($site["sitetype"]!=1) continue;

					$todogood=["option"=>$good["option"],"desc"=>$good["desc"],"rid"=>$to["rid"]];
					foreach($todogood["option"]["vv"] as $k=>$option)
					{
						if(isset($option["price"]))
						{
							foreach($option["price"] as $k1=>$v1)
							{
								$v1=str_replace([",","$"],"",$v1);
								$todogood["option"]["vv"][$k]["price"][$k1]=get_price($site["ruler"],$v1);
							}
						}			
					}
					loadsystemlink($site);
					if($this->mysite->checklink)
					{
						$result = $this->mysite->rebuiltcombine($todogood);
					}
					unset($this->mysite);
				}
				$json["status"]=1;
			}
			else
			{
				$json["msg"]="未找到发布产品";
			}				
		}
		else
		{
			$json["msg"]="商品不存在";
		}
		echo json_encode($json,JSON_UNESCAPED_UNICODE);
		die();
	} 

	public function updateimage($gid)
	{
		$good=$this->goods_model->getbyid($gid);
		if($good)
		{
			$newimg=unserialize($good["thumb"]);
			$option=unserialize($good["option"]);
			if($option && isset($option["vv"][0]["image"]))
			{
				foreach($option["vv"][0]["image"] as $va)
				{
					$newimg[]=$va;
				}
			}
			if($newimg)
			{
				$todo=$this->siteproduct_model->getitemsfilter(["productid"=>$gid]);
				if($todo)
				{
					foreach($todo as $to)
					{
						$site=$this->site_model->getitembyid($to["siteid"]);
						if($site["sitetype"]!=1) continue;
						loadsystemlink($site);
						if($this->mysite->checklink)
						{
							$post=["img"=>$newimg,"rid"=>$to["rid"]];
							$result = $this->mysite->upimage($post);
						}
						unset($this->mysite);
					}
				}
			}
		}
	}

	
	public function ajaxdel()
	{

		$return=["status"=>1];
		$cid=$this->input->post("cid");
		

		$product=$this->siteproduct_model->getitembyid($cid);
		if(!$product)
		{
			$return["status"]=0;
			$return["msg"]="记录不存在";			
		}
		else
		{
			$site=$this->site_model->getitembyid($product["siteid"]);
			loadsystemlink($site);
			if(!$this->mysite->checklink)
			{
				$return["status"]=0;
				$return["msg"]="请检查接口配置";	
			}
			else
			{
				$result = $this->mysite->delproduct($product);
				if($result=="ok")
				{
					$this->siteproduct_model->delitem($product["id"]);
				}
			}
		}

        echo json_encode($return);
		die();
		
	}
	
}
